<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\api\controller;
use think\Db;

class  Iphone extends \app\api\controller\Base {
    function validate_apple_pay($receipt_data){
        /**
         * 21000 App Store不能读取你提供的JSON对象
         * 21002 receipt-data域的数据有问题
         * 21003 receipt无法通过验证
         * 21004 提供的shared secret不匹配你账号中的shared secret
         * 21005 receipt服务器当前不可用
         * 21006 receipt合法，但是订阅已过期。服务器接收到这个状态码时，receipt数据仍然会解码并一起发送
         * 21007 receipt是Sandbox receipt，但却发送至生产系统的验证服务
         * 21008 receipt是生产receipt，但却发送至Sandbox环境的验证服务
         */
        function acurl($receipt_data, $sandbox=0){
            //小票信息
            $POSTFIELDS = array("receipt-data" => $receipt_data);
            $POSTFIELDS = json_encode($POSTFIELDS);

            //正式购买地址 沙盒购买地址
//            $url_buy     = "https://buy.itunes.apple.com/verifyReceipt";
            $url_buy     = "https://buy.itunes.apple.com/verifyReceipt";
            $url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
//            $url = $sandbox ? $url_sandbox : $url_buy;
            $url = $url_sandbox;

            //简单的curl
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
            $result = curl_exec($ch);
            curl_close($ch);
            return $result;
        }
        // 验证参数
        if (strlen($receipt_data)<20){
            $result=array(
                'status'=>false,
                'message'=>'非法参数'
            );
            return $result;
        }
        // 请求验证
        $html = acurl($receipt_data);
        $data = json_decode($html,true);

        // 如果是沙盒数据 则验证沙盒模式
        if($data['status']=='21007'){
            // 请求验证
            $html = acurl($receipt_data, 1);
            $data = json_decode($html,true);
            $data['sandbox'] = '1';
        }

        if (isset($_GET['debug'])) {
            exit(json_encode($data));
        }

        // 判断是否购买成功
        if(intval($data['status'])===0){
            $result=array(
                'status'=>true,
                'message'=>'购买成功'
            );
        }else{
            $result=array(
                'status'=>false,
                'message'=>'购买失败 status:'.$data['status']
            );
        }
        return $result;
    }

    public function apppay()
    {
        $param = $_POST['param'];
        $res = $this->validate_apple_pay($param);
        if($res['status']){
            // 验证通过 此处可以是修改数据库订单状态等操作

            $num = $_POST['order_number'];
            $info = Db::table('up_order')->where('order_number',$num)->find();
            $dataOrder = array();
            $dataOrder['order_trade_no'] = $_POST['transaction_id'];
            $dataOrder['order_boos_get'] = $info['order_money']*0.8;
            $dataOrder['order_user_pay'] = $info['order_money'];
            $dataOrder['order_ali_fund_bill_list'] = '';
            $dataOrder['order_ali_paytime'] = date('Y-m-d H:i:s');
            $dataOrder['order_status'] = 1;
            Db::startTrans();
            try{
//                Db::table('up_order')->where('order_number',$num)->update($dataOrder);
//                if($res){
                $change = Db::table('up_order')->where('order_number',$num)->field('order_user_id,order_long_type,order_long_id')->find();
                $have = Db::table('up_user_auth')
                    ->where('uauth_user_id',$change['order_user_id'])
                    ->where('uauth_type',$change['order_long_type'])
                    ->find();
                $today = date('Y-m-d');
                if($have){
                    $data = array();
                    $data['uauth_status'] = 1;
                    $plus = Db::table('up_user_auth_long')->where('long_id',$change['order_long_id'])->value('long_how');
                    if($have['uauth_end'] >= $today){
                        //========使用期限========
                        $dataOrder['order_start'] = $have['uauth_end'];
                        //=========end=======
                        $data['uauth_end'] = date("Y-m-d",strtotime("+$plus month",strtotime("{$have['uauth_end']}")));
                    }else{
                        //========使用期限========
                        $dataOrder['order_start'] = $today;
                        //=========end=======
                        $data['uauth_start'] = $today;
                        $data['uauth_time'] = date('Y-m-d H:i:s');
                        $data['uauth_end'] = date("Y-m-d",strtotime("+$plus month",strtotime("{$today}")));
                    }
                    //========使用期限========
                    $dataOrder['order_end'] = $data['uauth_end'];
                    //=========end=======
                    Db::table('up_user_auth')
                        ->where('uauth_user_id',$change['order_user_id'])
                        ->where('uauth_type',$change['order_long_type'])->update($data);
                }else{
                    $plus = Db::table('up_user_auth_long')->where('long_id',$change['order_long_id'])->value('long_how');
                    $data = array();
                    $data['uauth_user_id'] = $change['order_user_id'];
                    $data['uauth_long_id'] = $change['order_long_id'];
                    $data['uauth_type'] = $change['order_long_type'];
                    $data['uauth_start'] = $today;
                    $data['uauth_end'] = date("Y-m-d",strtotime("+$plus month",strtotime("{$today}")));
                    $data['uauth_time'] = date('Y-m-d H:i:s');
                    //========使用期限========
                    $dataOrder['order_start'] = $today;
                    $dataOrder['order_end'] = $data['uauth_end'];
                    //=========end=======
                    Db::table('up_user_auth')->insert($data);
                }
                Db::table('up_order')->where('order_number',$num)->update($dataOrder);
                //=======================入消息库===============================
                $pai[2] = '铜';
                $pai[3] = '银';
                $pai[4] = '金';
                $notice = array();
                $notice['n_title'] = '购买权限成功';
                $notice['n_content'] = "您已经成功购买{$pai[$change['order_long_type']]}牌召集令，快来使用吧";
                $notice['n_createtime'] = date('Y-m-d H:i:s');
                $notice['n_type'] = 3;
                $notice['n_send_type'] = 2;
                $notice['n_user_id'] = $change['order_user_id'];
                $notice['n_read_users'] = ',0,';
                $notice['n_clear_users'] = ',0,';
                Db::table('up_notice')->insert($notice);
                //========================入消息库end==============================
                Db::commit();
                $this->Jpush("{$change['order_user_id']}", '购买权限成功', 1, array('a'=>'b'));
                return json_encode(['status'=>200,'msg'=>'购买成功']);
//                }
            }catch (\Exception $e) {
                Db::rollback();
                return json_encode(['status'=>0,'msg'=>'购买失败']);
            }
        }else{
            // 验证不通过
            return json_encode(['status'=>0,'msg'=>'购买失败']);
        }
    }

    /**
     * 获取支付id信息
     * @return string
     */
    public function getPayInfo()
    {
        extract(input());
//        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
//        if($auth == false){
//            $this->apiError(301);
//        }
        $long = Db::table('up_user_auth_long')
            ->where('long_id',$long_id)->find();
        $data = array();
        $data['order_number'] = time().rand(1000000,9999999);
        $data['order_user_id'] = $user_id;
        $data['order_long_id'] = $long_id;
        $data['order_datetime'] = date('Y-m-d H:i:s');
        $data['order_type'] = 3;
        $data['order_money'] = $long['long_money'];
        $data['order_long_type'] = $long['long_type'];
        $res = Db::table('up_order')->insert($data);
        if($res){
            return json_encode(['status'=>200,'msg'=>$long['long_iphone_id'],'order_number'=>$data['order_number']]);
        }else{
            return json_encode(['status'=>0,'msg'=>'订单生成失败']);
        }
    }

}